package com.qkun.library.base.receiver;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.text.TextUtils;
import android.util.ArrayMap;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;

import com.qkun.library.base.BaseBroadcastReceiver;
import com.qkun.library.utils.MyLog;
import com.qkun.library.utils.Utils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author qinkun
 * @date 11/21 0021 14:36
 * @description
 */
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
public class AnnotationBroadcastReceiver extends BaseBroadcastReceiver {

    private final ArrayMap<String, Method> mMethodArrayMap = new ArrayMap<>();

    @Override
    protected final void onReceive(Context context, @NonNull Intent intent, @NonNull String action) {
        try {
            Method method = mMethodArrayMap.get(action);
            if (Utils.nonNull(method)) {
                method.setAccessible(true);
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O
                        || method.getParameterCount() == 0) {
                    method.invoke(this);
                } else {
                    onReceiveCustom(context, intent, method);
                }
            }
        } catch (IllegalAccessException | InvocationTargetException e) {
            MyLog.e(e);
        }
    }

    protected void onReceiveCustom(Context context, @NonNull Intent intent, @NonNull Method method) {
    }

    private void bind() {
        Class<?> annotationParent = this.getClass();
        MyLog.d(annotationParent.getName());
        Method[] methods = annotationParent.getDeclaredMethods();
        for (Method method : methods) {
            //找到添加了OnClick注解的方法
            Action action = method.getAnnotation(Action.class);
            if (Utils.nonNull(action) && !TextUtils.isEmpty(action.value())) {
                mMethodArrayMap.put(action.value(), method);
            }
        }
    }

    public final void register(@NonNull Context context) {
        bind();
        IntentFilter intentFilter = new IntentFilter();
        for (String action : mMethodArrayMap.keySet()) {
            intentFilter.addAction(action);
        }
        super.register(context, intentFilter);
    }

}
